package leecode

import "strconv"

func evalRPN(tokens []string) int {
	if len(tokens) == 1 {
		temp, _ := strconv.Atoi(tokens[0])
		return temp
	}
	var result int
	prn := make([]int, 0, len(tokens))
	for _, value := range tokens {
		if value == "+" {
			//取出栈顶的两个元素相加
			result = prn[len(prn)-1] + prn[len(prn)-2]
			//将得到的结果压栈
			prn = prn[:len(prn)-2]
			prn = append(prn, result)
		} else if value == "-" {
			//取出栈顶的两个元素相减
			result = prn[len(prn)-2] - prn[len(prn)-1]
			//将结果压栈
			prn = prn[:len(prn)-2]
			prn = append(prn, result)
		} else if value == "*" {
			//取出栈顶的两个元素相乘
			result = prn[len(prn)-1] * prn[len(prn)-2]
			//将结果压栈
			prn = prn[:len(prn)-2]
			prn = append(prn, result)
		} else if value == "/" {
			result = prn[len(prn)-2] / prn[len(prn)-1]
			//将结果压栈
			prn = prn[:len(prn)-2]
			prn = append(prn, result)
		} else {
			temp, _ := strconv.Atoi(value)
			prn = append(prn, temp)
		}
	}
	return result
}
